import { 
  getGoodsListData
} from './network/goodsList.js'; 
$(function() {
  class GoodsList {
    constructor() {
      this.init();
    }
    init() {
      //筛选图片比例正则
      this.img_reg = /(?<=\_)\d+x\d+(\.jpg|\.jpeg|\.png|\.webp|\.gif)$/g;
      //请求参数
      //以防刷新页面数据丢失，使用本地存储
      this.options = {
        page: sessionStorage.getItem('page') ? sessionStorage.getItem('page') : 1,
        sort: sessionStorage.getItem('sortKey') ? sessionStorage.getItem('sortKey') : null,
        minPrice: sessionStorage.getItem('priceStage') ? JSON.parse(sessionStorage.getItem('priceStage')).min : null,
        maxPrice: sessionStorage.getItem('priceStage') ? JSON.parse(sessionStorage.getItem('priceStage')).max : null,
      }
      this.initDom();
      //给菜单项添加类目id
      this.addCateId();
      //初始化总页数变量
      this.total = 0;
      this.pagination_size = 7,
      //渲染商品列表参数
      this.loadGoodsListData(this.options);
      //获取分页器容器
      this.pagination_wrapper = $('#my-pagination');
      //绑定事件
      this.bindEvent();
    }
    initDom() {
      //获取菜单列表
      this.menus = $('.goods-list-title .top-cate li');
      //获取排序列表
      this.sort_list = $('.filter-goods .sort');
      //获取价格分段列表
      this.price_list = $('.filter-goods .stage');
      //获取确定按钮
      this.confim_btn = $('.filter-goods .confirm');
      //获取商品列表
      this.goods_list_wrapper = $('.goods-list-wrapper ul.goods-list');
    }
    //绑定事件
    bindEvent() {
      let _this = this;
      //点击商品跳转到详情页
      this.goods_list_wrapper.on('click', 'li', function() {
        let goodslink = $(this).attr('data-link');
        window.open(goodslink);
      });
      //菜单列表点击发送请求获取数据渲染
      this.menus.on('click', function() {
        sessionStorage.setItem('menusActiveIndex', $(this).index());
        let cateid = $(this).attr('data-cateid');
        sessionStorage.setItem('sortKey', "pop");
        sessionStorage.setItem('sortActiveIndex', 0);
        sessionStorage.setItem('priceStage', '');
        location.hash = `#cateid=${cateid}`;
        location.reload();
      });

      //排序方法按钮
      this.sort_list.on('click', 'li.choice', function() {
        sessionStorage.setItem('sortActiveIndex', parseInt($(this).index() / 2));
        let sortKey = $(this).attr('data-sortKey');
        _this.options.sort = sortKey;
        _this.loadGoodsListData(_this.options);
        //记录排序方法
        sessionStorage.setItem('sortKey', sortKey);
      });

      //价格区间按钮
      this.price_list.on('click', 'div.price-stage', function() {
        let min = $(this).children('span.min').text();
        let max = $(this).children('span.max').text();
        let priceStage = {
          min,
          max
        }
        _this.options.minPrice = priceStage.min;
        _this.options.maxPrice = priceStage.max;
        _this.loadGoodsListData(_this.options);
        //记录价格区间
        sessionStorage.setItem('priceStage', JSON.stringify(priceStage));
      });

      //输入价额区间
      this.confim_btn.on('click', function() {
        let min = $('.filter-goods .range .min').val();
        let max = $('.filter-goods .range .max').val();
        let priceStage = {
          min,
          max
        }
        _this.options.minPrice = priceStage.min;
        _this.options.maxPrice = priceStage.max;
        _this.loadGoodsListData(_this.options);
        //记录价格区间
        sessionStorage.setItem('priceStage', JSON.stringify(priceStage));
        $('.filter-goods .range .min').val('');
        $('.filter-goods .range .max').val('');
      });

      //分页器页码点击事件
      this.pagination_wrapper.on('click', 'span', function() {
        _this.options.page = $(this).text();
        sessionStorage.setItem('page', _this.options.page);
        _this.loadGoodsListData(_this.options);
      });
      //分页器首尾页绑定事件
      this.pagination_wrapper.on('click', 'strong', function() {
        if($(this).hasClass('first-page')) {
          _this.options.page = 1;
        }else if($(this).hasClass('last-page')) {
          _this.options.page = _this.total;
        }
        _this.loadGoodsListData(_this.options);
      });
      //分页器前进后退按钮绑定事件
      this.pagination_wrapper.on('click', 'i', function() {
        if($(this).hasClass('prev-page')) {
          _this.options.page--;
        }else if($(this).hasClass('next-page')) {
          _this.options.page++;
        }
        _this.loadGoodsListData(_this.options);
      });
      //分页器禁止选中默认行为
      this.pagination_wrapper.on('selectstart', (e) => {
        if(e.preventDefault) {
          e.preventDefault();
        }else {{
          e.returnValue = false;
        }}
      });
    }

    //渲染分页器
    renderPagination() {
      if(this.total < this.pagination_size) {
        this.pagination_size = this.total;
      }
      let str = ``;
      let start = parseInt(this.options.page) - Math.floor(this.pagination_size / 2);
      let end = parseInt(this.options.page) + Math.floor(this.pagination_size / 2);
      if(start < 1) {
        start = 1;
        end = this.pagination_size;
      }
      if(end > this.total) {
        end = this.total;
        start = this.total - this.pagination_size + 1;
      }
      if(start > 1) {
        str += `
        <i class="iconfont icon-zuojiantou prev-page"></i>
        `;
      }
      str += `
        <strong class='first-page'>首页</strong>
      `;
      if(start > 1) {
        str += `
          <span>1</span>
          <b>...</b>
        `;
      }
      for(let i=start; i<=end; i++) {
        str += `<span ${parseInt(this.options.page) === i ? "class='active'" : ""}>${i}</span>`;
      }
      if(end < this.total) {
        str += `
          <b>...</b>
          <span>${this.total}</span>
        `;
      }
      str += `
        <strong class='last-page'>尾页</strong>
      `;
      if(end < this.total) {
        str += `
          <i class="iconfont icon-youjiantou next-page"></i>
        `;
      }
      this.pagination_wrapper.html(str);
    }

    //获取商品列表数据并渲染
    loadGoodsListData(options) {
      getGoodsListData(options, (res) => {
        //保存总页数
        this.total = Math.ceil(res.result.wall.pager.total / res.result.wall.pager.perPage);
        this.renderMenuActive();
        this.renderSortList(res);
        this.renderPriceList(res);
        this.renderGoodsList(res);
        this.renderPagination();
      });
    }
    //渲染活跃的菜单项
    renderMenuActive() {
      let index = sessionStorage.getItem('menusActiveIndex');
      this.menus.eq(index).addClass('active').siblings().removeClass('active');
    }
    //渲染商品列表
    renderGoodsList(res) {
      let data = res.result.wall.docs;
      let html = data.map(item => {
        if(item) {
          //计算图片高度
          let size = this.getImgSize(item.img);
          return `
          <li data-link="${item.link}">
            <div class="img">
              <img data-src="${item.img}" alt="" height="${218 / size.width * size.height}">
            </div>
            <div class="goods-info">
              <p class="title">
                ${item.title}
              </p>
              <p class="ginfo">
                <span class="price">
                  ￥${item.price.toFixed(2)}
                </span>
                <span class='store'>
                  <i></i>
                  <span class='store-count'>${item.cfav}</span>
                </span>
              </p>
            </div>
          </li>
          `
          }
      }).join('');
      this.goods_list_wrapper.html(html);
      new WaterFall('ul.goods-list', 'ul.goods-list li')
      new LazyLoad('.goods-list-wrapper ul.goods-list li img');
    }
    //渲染价格分段列表
    renderPriceList(res) {
      let data = res.result.priceList;
      let html = data.map(item => {
        return  `
          <div class="fl price-stage"><span class="min">${item.min}</span> - <span class="max">${item.max}</span></div>
        `;
      }).join('');
      this.price_list.html(html)
    }
    //渲染排序方法列表
    renderSortList(res) {
      let data = res.result.sortList;
      let html = ``;
      let sortActiveIndex = sessionStorage.getItem('sortActiveIndex') ? parseInt(sessionStorage.getItem('sortActiveIndex')) : 0;
      $.each(data, (index, item) => {
        if(index === 0) {
          html += `<li data-sortKey='${item.sortKey}' class='choice ${sortActiveIndex === index ? "active" : ""}'>${item.title}</li>`;
        }else {
          html += `
            <li class='line'>|</li>
            <li data-sortKey='${item.sortKey}' class='choice ${sortActiveIndex === index ? "active" : ""}'>${item.title}</li>
          `;
        }
      })
      this.sort_list.html(html);
    }
    //给菜单项添加类目id
    addCateId() {
      let menus_list = JSON.parse(localStorage.getItem('menus'));
      $.each(menus_list, (index, item) => {
        this.menus.eq(index).attr('data-cateid', item);
      });
    }
    //拿到链接中的图片宽高
    getImgSize(link) {
      let res = link.match(this.img_reg).join('').split('.')[0].split('x');
      return {
        width: res[0],
        height: res[1]
      }

    }
  }

  new GoodsList();
});